package com.ljf.common.api.service.impl;

import com.ljf.common.domain.service.NoDBBasisDomainService;
import com.ljf.common.domain.validator.NoDbBasisValidator;
import com.ljf.common.service.INoDBBasisService;
import org.springframework.context.ApplicationContext;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.ParameterizedType;

/**
 * 基础服务接口实现-无数据表
 *
 * @author LJF
 * @since 2024-01-25
 */
public class NoDBBasisServiceImpl<D extends NoDBBasisDomainService, C extends NoDbBasisValidator> implements INoDBBasisService {

    @Resource
    private ApplicationContext applicationContext;

    protected D domainService;

    private Class<D> domainServiceClass;

    protected C validator;

    private Class<C> validatorClass;

    @PostConstruct
    public void init() {
        this.getValidator();
        this.getDomainService();
    }

    /**
     * 获取领域服务对象
     *
     * @return
     */
    private C getValidator() {
        if (this.validator == null) {
            Class<C> sampleObjectCallBack = this.getSuperClassGenricValidatorType(1);
            this.validator = this.applicationContext.getBean(sampleObjectCallBack);
        }
        return this.validator;
    }

    /**
     * 获取服务Bean类型 领域服务
     *
     * @param index
     * @return
     */
    private Class<C> getSuperClassGenricValidatorType(int index) {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        int count = type.getActualTypeArguments().length;
        if (count > 0) {
            this.validatorClass = (Class) type.getActualTypeArguments()[index];
        }
        return this.validatorClass;
    }

    /**
     * 获取领域服务对象
     *
     * @return
     */
    private D getDomainService() {
        if (this.domainService == null) {
            Class<D> sampleObjectCallBack = this.getSuperClassGenricDomainType(0);
            this.domainService = this.applicationContext.getBean(sampleObjectCallBack);
        }
        return this.domainService;
    }

    /**
     * 获取服务Bean类型 领域服务
     *
     * @param index
     * @return
     */
    private Class<D> getSuperClassGenricDomainType(int index) {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        int count = type.getActualTypeArguments().length;
        if (count > 0) {
            this.domainServiceClass = (Class) type.getActualTypeArguments()[index];
        }
        return this.domainServiceClass;
    }

}
